package com.guaoran.algorithm.binary.tree;

import com.guaoran.algorithm.common.CommonUtil;
import com.guaoran.algorithm.entity.TreeNode;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Auth gucheng
 * @Desc 展示二叉树右侧视图
 * https://leetcode.com/problems/binary-tree-right-side-view/
 * @Date 2021/1/20 下午1:24
 */
public class BinaryTreeRightSideView {
    public static void main(String[] args) {
        TreeNode treeNode = CommonUtil.createTreeNode(new Integer[]{1, 2, 3, null, 5, null, 4});
        System.out.println(CommonUtil.readTreeNode(treeNode));
        List<Integer> integers = rightSideView(treeNode);
        System.out.println(integers);
    }
    public static List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean findRight = false;
        while (!queue.isEmpty()){
            findRight = false;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if(!findRight){
                    result.add(node.val);
                    findRight = true;
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                if(node.left != null){
                    queue.offer(node.left);
                }
            }
        }
        return result;
    }
}
